package com.fy.config;

import com.fy.common.ConfigUtils;
import com.fy.common.Result;
import com.fy.exception.LoginException;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    @Autowired
    private ConfigUtils configUtils;

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class) //表示让Spring捕获到所有抛出的SignException异常，并交由这个被注解的方法处理。
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)  //表示设置状态码。
    Result handleException(Exception e){
       e.printStackTrace();
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(value = LoginException.class)
    Result handleLoginException(HttpServletRequest request, HttpServletResponse response, LoginException e) {
        logger.error("登录异常：---Host {} invokes url {} ERROR: {}", request.getRemoteHost(), request.getRequestURL(), e.getMessage());
        response.setStatus(e.getCode());
        return Result.error(e.getCode(),e.getMessage());
    }
}